package com.siemens.industrial.web.mvc.dao.admin;

import com.siemens.industrial.model.admin.SystemConfig;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by qupen on 2016/9/18.
 */
@Service
public class SystemConfigDao {
    @Resource
    JdbcTemplate jdbcTemplate;

    private static final String getSystemConfigListQuery = "SELECT * FROM `siemens`.`system_config`";
    private static final String getOneByKeyQuery = "SELECT * FROM `siemens`.`system_config` WHERE `system_key`=?";
    private static final String addSystemConfigQuery = "INSERT INTO `siemens`.`system_config` (`system_key`,`system_name`,`system_value`) VALUES (?,?,?)";
    private static final String updateSystemConfigQuery = "UPDATE `siemens`.`system_config` SET `system_name`=?,`system_value`=? WHERE `system_key`=?";
    private static final String deleteSystemConfigQueryByKey = "DELETE FROM `siemens`.`system_config` WHERE `system_key`=?;";

    public List<SystemConfig> getConfigList() {
        return jdbcTemplate.query(getSystemConfigListQuery, SystemConfig.getRowMapper());
    }

    public SystemConfig findOneByKey(String systemKey) {
        try {
            return jdbcTemplate.queryForObject(getOneByKeyQuery, new Object[]{systemKey}, SystemConfig.getRowMapper());
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    public int updateByKey(SystemConfig systemConfig) {
        return jdbcTemplate.update(updateSystemConfigQuery, pss -> {
            pss.setString(1, systemConfig.getSystemName());
            pss.setString(2, systemConfig.getSystemValue());
            pss.setString(3, systemConfig.getSystemKey());
        });
    }

    public int save(SystemConfig systemConfig) {
      return  jdbcTemplate.update(addSystemConfigQuery, pss -> {
            pss.setString(1, systemConfig.getSystemKey());
            pss.setString(2, systemConfig.getSystemName());
            pss.setString(3, systemConfig.getSystemValue());
        });
    }

    public void deleteByKey(String configKey) {
        jdbcTemplate.update(deleteSystemConfigQueryByKey,configKey);
    }
}
